using Microsoft.AspNetCore.Http;

namespace JGSY.CMS.LowCode.Platform.Infrastructure.Services
{
    /// <summary>
    /// 租户上下文服务
    /// 负责在整个请求生命周期中维护当前租户信息
    /// </summary>
    public interface ITenantContext
    {
        /// <summary>
        /// 当前租户ID（字符串格式）
        /// </summary>
        string? TenantId { get; }

        /// <summary>
        /// 当前租户ID（长整型格式，用于数据库查询）
        /// </summary>
        long? CurrentTenantId { get; }

        /// <summary>
        /// 设置当前租户ID
        /// </summary>
        /// <param name="tenantId">租户ID</param>
        void SetTenant(string tenantId);

        /// <summary>
        /// 清除当前租户
        /// </summary>
        void ClearTenant();

        /// <summary>
        /// 是否已设置租户
        /// </summary>
        bool HasTenant { get; }
    }

    /// <summary>
    /// 租户上下文服务实现
    /// </summary>
    public class TenantContext : ITenantContext
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private const string TenantIdKey = "TenantId";

        public TenantContext(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }

        /// <summary>
        /// 当前租户ID（字符串格式）
        /// </summary>
        public string? TenantId => _httpContextAccessor.HttpContext?.Items[TenantIdKey] as string;

        /// <summary>
        /// 当前租户ID（长整型格式，用于数据库查询）
        /// </summary>
        public long? CurrentTenantId
        {
            get
            {
                var tenantIdStr = TenantId;
                if (string.IsNullOrEmpty(tenantIdStr))
                    return null;
                
                return long.TryParse(tenantIdStr, out var tenantId) ? tenantId : null;
            }
        }

        /// <summary>
        /// 设置当前租户ID
        /// </summary>
        public void SetTenant(string tenantId)
        {
            if (_httpContextAccessor.HttpContext != null)
            {
                _httpContextAccessor.HttpContext.Items[TenantIdKey] = tenantId;
            }
        }

        /// <summary>
        /// 清除当前租户
        /// </summary>
        public void ClearTenant()
        {
            if (_httpContextAccessor.HttpContext != null)
            {
                _httpContextAccessor.HttpContext.Items.Remove(TenantIdKey);
            }
        }

        /// <summary>
        /// 是否已设置租户
        /// </summary>
        public bool HasTenant => !string.IsNullOrEmpty(TenantId);
    }
}
